var ports = require("../../utils/ports.js")
var app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pointNum: 0,
    expressTotal: 0,
    orderAmountFreeFare: 0,
    MemberBonusList: [],
    current: 0,
    pointToPrice: 0,
    couponPrice: 0,
    tablist: [{
      id: 0,
      name: '店内用餐'
    }, {
      id: 1,
      name: '外送'
    }],
    paylist: [{
      name: 'monthpay',
      value: '月结支付',
      amount: ''
    },{
      name: 'amountpay',
      value: '余额支付',
      amount: ''
    },{
      name: 'wxpay',
      value: '微信支付',
      amount: ''
    }],
    payfor: 'wxpay',
    pointCheck: false
  },
  getOneIndex: function (e) {
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    if (index == that.data.current) {
      return
    }
    that.setData({
      current: index
    })
    that.editRealTotal()
  },
  radioChange(e) {
    this.data.payfor = e.detail.value  
    const items = this.data.paylist
    for (let i = 0, len = items.length; i < len; ++i) {
      items[i].checked = items[i].value === e.detail.value
    }
    this.setData({
      paylist: items
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var type = options.type;
    that.getMyStatisticsData()
    if (type == 'cart') {
      that.getCartList()
    } else if (type == 'detail') {
      var goodsShopID = options.id
      var qty = options.qty
      var priceNow = options.realPrice
      var objectFeatureItemName1 = options.objectFeatureItemName1
      var objectFeatureItemID1 = options.objectFeatureItemID1
      that.getGoodsShopDetail(goodsShopID, qty, priceNow, objectFeatureItemID1, objectFeatureItemName1)
    } else {
      wx.showToast({
        title: '订单异常',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1000);
    }
  },
  //地址页面
  toAddress: function () {
    wx.navigateTo({
      url: '../address/address?type=order',
    })
  },
  getMemberStatisticsInfo() {
    let that = this
    ports.ModuleMember.getMemberStatisticsInfo({
    }, that, res => {
      if (res.data.header.code == 0) {
        that.setData({
          memberStatistics: res.data.body.data
        })
      } else {
        wx.showToast({
          title: res.data.header.msg,
          icon: 'none'
        })
      }
    })
  },
  //确认支付 外送
  paybtn: function () {
    var that = this
    var type = that.data.type //订单类型
    var data = {}
    data.paywayID = app.paywayID
    data.pointPrice = that.data.pointPrice
    var address = that.data.address
    if (that.data.current == 1 && !address) {
      wx.showToast({
        title: '请选择地址',
        icon: 'none'
      })
      return
    }
    var openid = wx.getStorageSync("USER_OPENID")
    if (!openid) {
      wx.showToast({
        title: '用户信息异常',
        icon: 'none'
      })
      return
    }
    if (that.data.objectFeatureItemID1) {
      data.objectFeatureItemID1 = that.data.objectFeatureItemID1
    }
    if (that.data.memberBonusID) {
      data.memberBonusID = that.data.memberBonusID
    }
    data.sendType = that.data.current == 0 ? 2 : 1
    if(that.data.current == 1){
      if(address){
        data.contactName = address.contactName
        data.address = address.shengName + address.shiName + address.xianName + address.name
        data.contactPhone = address.phone
      }else{
        wx.showToast({
          title: '请选择地址',
          icon: 'none'
        })
        return
      }
    }
    //余额校验
    if(that.data.payfor == 'amountpay' && that.data.statisticsData.cashBalance < that.data.realTotal){
      wx.showToast({
        title: '余额不足',
        icon: 'none'
      })
      return
    }else if(that.data.payfor == 'monthpay' && that.data.statisticsData.monthBalance < that.data.realTotal){
      wx.showToast({
        title: '月结额不足',
        icon: 'none'
      })
      return
    }
    wx.showToast({
      title: '提交中',
      icon: 'loading',
      mask: true
    })
    if (type == 'cart') {
      that.createMemberOrderFromCart(data)
    } else if (type == 'detail') {
      data.qty = that.data.qty
      data.goodsShopID = that.data.goodsShopDetail.id
      that.createMemberOrder(data)
    } else {
      wx.showToast({
        title: '订单异常',
        icon: 'none'
      })
      return
    }
  },
  //红包选择
  onHide: function () { },
  //购物车列表
  getCartList() {
    var that = this
    that.getExpressInfo()
    ports.ModuleCart.getCartList({
      isSelect: 1
    }, that, res => {
      if (res.data.header.code == 0) {
        var goodsList = res.data.body.data[0].goodsList
        var total = 0;
        for (var i = 0; i < goodsList.length; i++) {
          total += goodsList[i].priceTotal
        }
        that.setData({
          total: total,
          realTotal: realtotal.toFixed(2),
          type: 'cart',
          cartList: res.data.body.data
        })
        that.editRealTotal()
        that.getMyMemberBonusList()
      } else {
        wx.showToast({
          title: res.data.header.msg,
          icon: 'none'
        })
      }
    })
  },
  //商品详情
  getGoodsShopDetail(goodsShopID, qty, priceNow, objectFeatureItemID1, objectFeatureItemName1) {
    var that = this
    that.getExpressInfo()
    //店铺商品详情
    ports.ModuleGoodsShop.getGoodsShopDetail({
      goodsShopID: goodsShopID,
      type: 2
    }, that, res => {
      if (res.data.header.code == 0) {
        that.setData({
          total: parseFloat(priceNow * qty).toFixed(2),
          qty: qty,
          type: 'detail',
          priceNow: priceNow,
          objectFeatureItemName1: objectFeatureItemName1,
          objectFeatureItemID1: objectFeatureItemID1,
          goodsShopDetail: res.data.body.data
        })
        that.editRealTotal()
        that.getMyMemberBonusList()
      }
    })
  },
  getExpressInfo() {
    var that = this
    //获取订单运费
    ports.ModuleGoodsShop.getParameterValueByCode({
      code: app.orderFare,
    }, that, res => {
      if (res.data.header.code == 0) {
        that.setData({
          expressTotal: parseFloat(res.data.body.data)
        })
      }
    })
    //获取包邮信息
    ports.ModuleGoodsShop.getParameterValueByCode({
      code: app.orderAmountFreeFare,
    }, that, res => {
      if (res.data.header.code == 0) {
        that.setData({
          orderAmountFreeFare: parseFloat(res.data.body.data)
        })
      }
    })
    //100积分抵扣金额
    ports.ModuleGoodsShop.getParameterValueByCode({
      code: app.point2Price,
    }, that, res => {
      if (res.data.header.code == 0) {
        that.setData({
          point2Price: res.data.body.data
        })
      }
    })
  },
  //选择红包
  showCoupon(e) {
    const that = this;
    that.setData({
      toggleCoupon: true,
    })
  },
  // 关闭遮罩和选择优惠券
  closeCoupon() {
    const that = this;
    that.setData({
      toggleCoupon: false
    })
  },
  //选择优惠券
  selcoupon(e) {
    var that = this
    var index = e.detail.index; //优惠券下标
    var MemberBonusList = that.data.MemberBonusList; //优惠券列表
    var couponPrice = 0; //优惠券金额
    var toggleCoupon = false; //优惠券弹框
    var useCoupon = false; //是否使用优惠券
    var memberBonusID = '' //红包id
    for (var i = 0; i < MemberBonusList.length; i++) {
      if (index != i) {
        MemberBonusList[i]._checked = false
      } else {
        if (MemberBonusList[index]._checked) {
          MemberBonusList[index]._checked = false
          couponPrice = 0;
        } else {
          useCoupon = true
          MemberBonusList[index]._checked = true
          couponPrice = MemberBonusList[index].amount
          memberBonusID = MemberBonusList[index].id
        }
      }
    }
    that.setData({
      memberBonusID,
      couponPrice,
      useCoupon,
      toggleCoupon,
      MemberBonusList,
    })
    that.editRealTotal()
  },
  //不使用
  noused() {
    const that = this;
    that.setData({
      toggleCoupon: false,
    })
  },
  //优惠券列表
  getMyMemberBonusList() {
    var that = this
    var data = {}
    data.pageNumber = 999
    data.status = 1
    ports.ModuleBonus.getMyMemberBonusList(data, that, res => {
      if (res.data.header.code == 0) {
        var MemberBonusList = res.data.body.data.rows
        var realMemberBonusList = []
        var bonusStartPrice = 0;
        for (var i = 0; i < MemberBonusList.length; i++) {
          bonusStartPrice = MemberBonusList[i].bonusStartPrice
          if (bonusStartPrice && parseFloat(bonusStartPrice) <= parseFloat(that.data.total)) {
            realMemberBonusList.push(MemberBonusList[i])
          }
        }
        that.setData({
          MemberBonusList: realMemberBonusList
        })
      }
    })
  },

  //会员钱包数据
  getMyStatisticsData() {
    var that = this
    ports.ModuleMember.getMyStatisticsData({}, that, res => {
      if (res.data.header.code == 0) {
        var memberStatistics = res.data.body.data
        var paylist = that.data.paylist
        paylist[0].amount = memberStatistics.monthBalance.toFixed(2)
        paylist[1].amount = memberStatistics.cashBalance.toFixed(2)
        that.setData({
          paylist,
          statisticsData:memberStatistics
        })
      }
    })
  },
  //商品详情创建订单
  createMemberOrder(data) {
    var that = this
    ports.ModuleMemberOrder.createMemberOrder(data, that, res => {
      if (res.data.header.code == 0) {
        let payData = {}
        payData.memberOrderID = res.data.body.data;
        if(that.data.payfor == 'wxpay') {
          payData.openid = wx.getStorageSync("USER_OPENID")
          payData.payWayID = app.wxPaywayID
          payData.body = '购买商品'
          that.appApplyMemberOrderPay(payData)
        } else if(that.data.payfor == 'amountpay'){
          payData.payWayID = app.balacnePaywayID
          that.balancePayMemberOrder(payData)
        } else if(that.data.payfor == 'monthpay'){
          payData.payWayID = app.monthPaywayID
          that.monthBalancePayMemberOrder(payData)
        } else {
          wx.showToast({
            title: '支付方式异常',
            icon: 'none'
          })
        }
      } else {
        wx.showToast({
          title: res.data.header.msg,
          icon: 'none'
        })
      }
    })
  },
  //购物车创建订单
  createMemberOrderFromCart(data) {
    var that = this;
    ports.ModuleMemberOrder.createMemberOrderFromCart(data, that, res => {
      if (res.data.header.code == 0) {
        let payData = {}
        payData.memberOrderID = res.data.body.data;
        if(that.data.payfor == 'wxpay') {
          payData.openid = wx.getStorageSync("USER_OPENID")
          payData.payWayID = app.wxPaywayID
          payData.body = '购买商品'
          that.appApplyMemberOrderPay(payData)
        } else if(that.data.payfor == 'amountpay'){
          payData.payWayID = app.balacnePaywayID
          that.balancePayMemberOrder(payData)
        } else if(that.data.payfor == 'monthpay'){
          payData.payWayID = app.monthPaywayID
          that.monthBalancePayMemberOrder(payData)
        } else {
          wx.showToast({
            title: '支付方式异常',
            icon: 'none'
          })
        }
      } else {
        wx.showToast({
          title: res.data.header.msg,
          icon: 'none'
        })
      }
    })
  },
  //余额支付
  balancePayMemberOrder(data) {
    var that = this
    ports.ModuleMemberOrder.balancePayMemberOrder(data, that, res => {
      if (res.data.header.code == 0) {
        wx.showToast({
          title: '支付成功',
          icon: 'none',
          mask: true,
          duration: 1000
        })
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/order/order',
          })
        }, 1000);
      } else {
        wx.showToast({
          title: res.data.header.msg,
          icon: 'none'
        })
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/order/order',
          })
        }, 1000);
      }
    })
  },
  //月结支付
  monthBalancePayMemberOrder(data) {
    var that = this
    ports.ModuleMemberOrder.monthBalancePayMemberOrder(data, that, res => {
      if (res.data.header.code == 0) {
        wx.showToast({
          title: '支付成功',
          icon: 'none',
          mask: true,
          duration: 1000
        })
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/order/order',
          })
        }, 1000);
      } else {
        wx.showToast({
          title: res.data.header.msg,
          icon: 'none'
        })
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/order/order',
          })
        }, 1000);
      }
    })
  },
  //申请订单wx支付
  appApplyMemberOrderPay(data) {
    var that = this
    ports.ModuleMemberOrder.appApplyMemberOrderPay(data, that, res => {
      if (res.data.header.code == 0) {
        var data = res.data.body;
        wx.requestPayment({
          timeStamp: data.timeStamp,
          nonceStr: data.nonceStr,
          package: data.package,
          signType: data.signType,
          paySign: data.paySign,
          success(res) {
            wx.showToast({
              title: '支付成功',
              icon: 'none',
              mask: true,
              duration: 1000
            })
            setTimeout(() => {
              wx.redirectTo({
                url: '/pages/order/order',
              })
            }, 1000);
          },
          fail() {
            wx.showToast({
              title: '取消支付',
              icon: 'none',
              mask: true,
              duration: 1000
            })
            setTimeout(() => {
              wx.redirectTo({
                url: '/pages/order/order',
              })
            }, 1000);
          }
        })
      } else {
        wx.showToast({
          title: res.data.header.msg,
          icon: 'none'
        })
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/order/order',
          })
        }, 1000);
      }
    })
  },
  checkPointBox(e){
    let pointCheck = this.data.pointCheck
    let that = this
    if(!pointCheck){
      let realTotal = that.data.realTotal
      let point2Price = that.data.point2Price
      if(realTotal <= point2Price){
        wx.showToast({
          title: '金额小于 ' + point2Price + '元，无法抵扣',
          icon:'none',
          duration:1000
        })
        that.setData({
          pointCheck: false
        })
        return
      }
      wx.showModal({
        title: '提示',
        content: '满100积分抵扣' + that.data.point2Price + '元',
        success(res) {
          if (res.confirm) {
            that.setData({
              pointCheck: !pointCheck
            })
            that.editRealTotal()
          }else{
            that.setData({
              pointCheck: false
            })
          }
        }
      })
    }else{
      
      that.setData({
        pointCheck: !pointCheck
      })
      that.editRealTotal()
    }
  },
  editRealTotal(){
    let that = this
    let couponPrice = parseFloat(that.data.couponPrice); //优惠券金额
    let total = parseFloat(that.data.total) //总价格
    
    let realTotal = total - couponPrice
    let pointPrice = that.getPointToPrice(realTotal)
    realTotal = realTotal - pointPrice

    let needExpressTotal = that.data.current == 0 ? 0 : parseFloat(that.data.expressTotal) //运费
    needExpressTotal = that.data.orderAmountFreeFare <= total ? 0 : needExpressTotal

    realTotal = realTotal + needExpressTotal
    that.setData({
      needExpressTotal: needExpressTotal,
      realTotal: realTotal.toFixed(2),
      pointPrice: pointPrice
    })
  },
  getPointToPrice(realTotal){
    let that = this
    if(!that.data.pointCheck){
      return 0;
    }
    let point = that.data.statisticsData.point
    let point2Price = parseFloat(that.data.point2Price)
    if(realTotal <= point2Price){
      return 0
    }
    let num = parseInt(realTotal / point2Price)
    let allNum = parseInt(point / point2Price)
    if(num < allNum) {
      return num * point2Price == realTotal ? (num - 1) * point2Price : num * point2Price
    }else {
      return allNum * point2Price
    }
  }
})